<?php
class Cut {

  public $url = '';
  public $parse_url = '';

  //获取章节图片地址 - dev
  public function getImagesUrl_ByFile($info, $data)
  {
    $this->url = $info['link'];
    $this->parse_url = parse_url($this->url);

    switch($this->parse_url['host']) {
      case 'www.leshen.com':
        $result = $this->getImagesUrl_ByFile_leshen($info, $data); break;
      default:
        $result = array(); break;
    }

    return $result;
  }

  public function getImagesUrl_ByFile_leshen($info, $data)
  {
    preg_match('/var qTcms_S_m_murl_e="(.+?)"/i', $data['results'], $out);
    if(empty($out[1])) {
      return false;
    }
    $file_text = base64_decode($out[1]);
    $file_text = explode('$qingtiandy$', $file_text);
    foreach ($file_text as &$value) {
      if(empty($value)) continue;
      $value = 'http://s.leshen.com:8080'.$value;
    }

    return $file_text;
  }

  //获取章节图片地址
  public function getImagesUrl($info, $data, $action)
  {
    $this->url = $info['link'];
    $this->parse_url = parse_url($this->url);

    switch($this->parse_url['host']) {
      case 'www.073.cc':
        $result = $this->getImagesUrl_073($info, $data, $action); break;
      case 'www.leshen.com':
        $result = $this->getImagesUrl_leshen($info, $data, $action); break;
      case 'sexi.xiee123.com':
        $result = $this->getImagesUrl_xiee123($info, $data, $action); break;
      case 'www.manhuadao.com':
        $result = $this->getImagesUrl_manhuadao($info, $data, $action); break;
      default:
        $result = array(); break;
    }

    return $result;
  }

  public function getImagesUrl_manhuadao($info, $data, $action)
  {
    $new_count = $old_count = $error_count = 0;
    foreach ($data as $url => &$cache_text) {
      //获取漫画图片地址
      if($cache_text == $action::CACHE_FETCH || $cache_text == $action::CACHE_EXISTS) { //下载成功或已存在的
        $cache_key = $info['pinyin']."/".md5($url);
        $cache = F($cache_key);
        if( is_array($cache) && isset($cache['results']) ) {
          $file = $cache['results'];
          preg_match('/\'fs\':(.+?),\'fc\'/is', $file, $out);
          preg_match_all('/\'(.+?)\'/i', $out[1], $matches);
          array_walk($matches[1], function(&$value, $key){
            if(!stristr($value, 'http://')) $value = "http://c5.mangafiles.com:88".$value;
          });
          $cache_text = $matches[1];
        }
      }

      //保存图片地址
      $dao_images = D('news_images');

      $images_data = array();
      $images_data['url'] = $url;
      $images_data['news_id'] = $info['id'];
      $images_data['url_key'] = substr(md5($url), 8, 16);
      $images_data['images1'] = json_encode($cache_text);
      $old = $dao_images->where("url_key='$images_data[url_key]'")->find();
      if(!empty($old)) {
        $old_count++;
        $dao_images->where("id=$old[id]")->save($images_data);
      }
      elseif($dao_images->create($images_data)) {
        $dao_images->add();
        $new_count++;
      }
      else {
        $info['errors'][] = $dao_images->getError().' '.$images_data['url_key'].' '.$images_data['url'];
        $error_count++;
      }
    }

    return compact('new_count', 'old_count', 'error_count', 'info');
  }

  public function getImagesUrl_xiee123($info, $data, $action)
  {
    $new_count = $old_count = $error_count = 0;
    foreach ($data as $url => &$cache_text) {
      //获取漫画图片地址
      if($cache_text == $action::CACHE_FETCH || $cache_text == $action::CACHE_EXISTS) { //下载成功或已存在的
        $cache_key = $info['pinyin']."/".md5($url);
        $cache = F($cache_key);
        if( is_array($cache) && isset($cache['results']) ) {
          $file = $cache['results'];
          preg_match('/<div class="content">(.+?)<\/div>/is', $file, $out);
          preg_match_all('/src=[\'|"](.+?)[\'|"]/i', $out[1], $matches);
          $cache_text = $matches[1];
        }
      }

      //保存图片地址
      $dao_images = D('news_images');

      $images_data = array();
      $images_data['url'] = $url;
      $images_data['news_id'] = $info['id'];
      $images_data['url_key'] = substr(md5($url), 8, 16);
      $images_data['images1'] = json_encode($cache_text);
      $old = $dao_images->where("url_key='$images_data[url_key]'")->find();
      if(!empty($old)) {
        $old_count++;
        $dao_images->where("id=$old[id]")->save($images_data);
      }
      elseif($dao_images->create($images_data)) {
        $dao_images->add();
        $new_count++;
      }
      else {
        $info['errors'][] = $dao_images->getError().' '.$images_data['url_key'].' '.$images_data['url'];
        $error_count++;
      }
    }

    return compact('new_count', 'old_count', 'error_count', 'info');
  }

  public function getImagesUrl_073($info, $data, $action)
  {
    $new_count = $old_count = $error_count = 0;
    foreach ($data as $url => &$cache_text) {
      //获取漫画图片地址
      if($cache_text == $action::CACHE_FETCH || $cache_text == $action::CACHE_EXISTS) { //下载成功或已存在的
        $cache_key = $info['pinyin']."/".md5($url);
        $cache = F($cache_key);
        if( is_array($cache) && isset($cache['results']) ) {
          $file = $cache['results'];
          preg_match('/eval.+?\{\}\)\)/is', $file, $match);
          $jsdecode = jsdecode($match[0]);
          preg_match_all('/url=(.+?)\\\\\'/', $jsdecode, $matches);
          foreach ($matches[1] as $image_key => &$image) {
            $image = urldecode($image);
            $image = iconv('gbk', 'utf-8//IGNORE', $image);
            if( substr($image, 0, 7) != 'http://' ) unset($matches[1][$image_key]);
          }
          $cache_text = $matches[1];
        }
      }

      //保存图片地址
      $dao_images = D('news_images');

      $images_data = array();
      $images_data['url'] = $url;
      $images_data['news_id'] = $info['id'];
      $images_data['url_key'] = substr(md5($url), 8, 16);
      $images_data['images1'] = json_encode($cache_text);
      $old = $dao_images->where("url_key='$images_data[url_key]'")->find();
      if(!empty($old)) {
        $old_count++;
      }
      elseif($dao_images->create($images_data)) {
        $dao_images->add();
        $new_count++;
      }
      else {
        $info['errors'][] = $dao_images->getError().' '.$images_data['url_key'].' '.$images_data['url'];
        $error_count++;
      }
    }

    return compact('new_count', 'old_count', 'error_count', 'info');
  }

  public function getImagesUrl_leshen($info, $data, $action)
  {
    $new_count = $old_count = $error_count = 0;
    foreach ($data as $url => &$cache_text) {
      //获取漫画图片地址
      if($cache_text == $action::CACHE_FETCH || $cache_text == $action::CACHE_EXISTS) { //下载成功或已存在的
        $cache_key = $info['pinyin']."/".md5($url);
        $cache = F($cache_key);
        if( is_array($cache) && isset($cache['results']) ) {
          $file = $cache['results'];
          preg_match('/var qTcms_S_m_murl_e="(.+?)"/i', $file, $out);
          $cache_text = base64_decode($out[1]);
          $cache_text = explode('$qingtiandy$', $cache_text);
          foreach ($cache_text as &$value) {
            $value = 'http://s.leshen.com:8080'.$value;
          }
        }
      }

      //保存图片地址
      $dao_images = D('news_images');

      $images_data = array();
      $images_data['url'] = $url;
      $images_data['news_id'] = $info['id'];
      $images_data['url_key'] = substr(md5($url), 8, 16);
      $images_data['images1'] = json_encode($cache_text);
      $old = $dao_images->where("url_key='$images_data[url_key]'")->find();
      if(!empty($old)) {
        $old_count++;
        $dao_images->where("id=$old[id]")->save($images_data);
      }
      elseif($dao_images->create($images_data)) {
        $dao_images->add();
        $new_count++;
      }
      else {
        $info['errors'][] = $dao_images->getError().' '.$images_data['url_key'].' '.$images_data['url'];
        $error_count++;
      }
    }

    return compact('new_count', 'old_count', 'error_count', 'info');
  }

  //截取data
  public function getData($file, $info)
  {
    $this->url = $info['link'];
    $this->parse_url = parse_url($this->url);

    switch($this->parse_url['host']) {
      case 'www.leshen.com':
        $result = $this->getData_leshen($file, $info); break;
      case 'www.manhuadao.com':
        $result = $this->getData_manhuadao($file); break;
      default:
        $result = array(); break;
    }

    return $result;
  }

  //http://www.manhuadao.com/book/jinjidejuren
  protected function getData_manhuadao($file)
  {
    $data = array();

    //标题
    preg_match('/<h1>(.+?)<\/h1>/i', $file, $match);
    $data['title']  = trim(strip_tags($match[1]));
    $data['pinyin'] = Pinyin($data['title']);
    $data['link'] = $this->url;
    $data['addtime'] = time();

    //作者
    preg_match('/<strong>漫画作者：<\/strong>(.+?)<\/a>/i', $file, $match);
    $data['author'] = trim(strip_tags($match[1]));

    //状态
    preg_match('/<strong>漫画状态：<\/strong>(.+?)<\/span>/i', $file, $match);
    $data['status'] = trim(strip_tags($match[1]));

    //类型
    preg_match('/<strong>漫画剧情：<\/strong>(.+?)<\/a>/i', $file, $match);
    $data['type'] = trim(strip_tags($match[1]));

    //封面
    preg_match('/<p class="hcover"><img src="(.+?)"/is', $file, $match);
    $data['thumb'] = trim($match[1]);
    if( !stristr($data['thumb'], 'http://') ) {
      $data['thumb'] = 'http://'.$this->parse_url['host'].$data['thumb'];
    }
    //保存封面
    if(!empty($data['thumb'])) {
      $pinyin = $data['pinyin'];
      if(empty($pinyin)) $pinyin = date("Ym");
      $newDir = "Public/images/".$pinyin."/";
      if( !file_exists($newDir) ){
        mkdir($newDir);
      }
      $thumb = file_get_contents($data['thumb']);
      if($thumb) {
        $filename = $newDir.md5($data['thumb']).'.jpg';
        file_put_contents($filename, $thumb);
        $data['thumb'] = 'http://image.lnpan.com/'.$filename;
      }
    }
    //区域
    preg_match('/<strong>漫画地区：<\/strong>(.+?)<\/a>/i', $file, $match);
    $data['area'] = trim(strip_tags($match[1]));

    //简介
    preg_match('/<div id="intro-all"[^>]*>(.+?)<\/div>/is', $file, $match);
    $data['info'] = trim(strip_tags($match[1]));

    //章节
    $chapter_count = 0;
    $data['chapter2'] = array();
    preg_match_all('/<h4><span>(.+?)<\/span><\/h4>/i', $file, $matches1); //标题
    preg_match_all('/<\/h4><div class="chapter-list[^>]*>(.+?)<\/ul><\/div>/is', $file, $matches2); //章节列表
    foreach ($matches2[1] as $k=>$itemlist) {
      $title = trim(strip_tags($matches1[1][$k]));
      preg_match_all('/href="(.+?)" title="(.+?)"/i', $itemlist, $matches);
      $tmp = array();
      foreach ($matches[2] as $key => $value) {
        $link = $matches[1][$key];
        if(!stristr($link, 'http://')) $link = "http://".$this->parse_url['host'].$link;
        if(mb_substr($value, 0, 1, 'utf-8') == '第') $value = mb_substr($value, 1, 100, 'utf-8');
        $tmp[$link] = $value;
        $chapter_count++;
      }
      $data['chapter2'][$title] = $tmp;
    }
    $data['chapter'] = json_encode($data['chapter2']);
    $data['chapter_count'] = $chapter_count;

    return $data;
  }

  //http://www.leshen.com/mm/ChaoJiFanDouShaoNian.html
  protected function getData_leshen($file, $info)
  {
    $data = array();
    //章节
    $chapters = $this->getChapters_leshen($file, null);
    $data['chapter'] = $chapters['list'];
    $data['chapter_count'] = $chapters['count'];
    $data['chapter_update'] = $chapters['last'];

    $file = iconv('gb2312', 'utf-8//IGNORE', $file);

    //标题
    preg_match('/<h1>(.+?)<\/h1>/i', $file, $match);
    $data['title2'] = trim(strip_tags($match[1]));
    $data['title2'] = str_replace('漫画', '', $data['title2']);
    $data['addtime'] = time();

    //简介
    preg_match('/<div id="intro1" class="introduction">(.+?)<\/div>/is', $file, $match);
    $data['info'] = trim(strip_tags($match[1]));

    //作者
    preg_match('/<em>原著作者：<\/em>(.+?)<\/p>/is', $file, $match);
    $data['author'] = trim(strip_tags($match[1]));

    //状态
    preg_match('/<em>漫画状态：<\/em>(.+?)<\/p>/is', $file, $match);
    $data['status'] = trim(strip_tags($match[1]));

    //区域
    preg_match('/<em>漫画区域：<\/em>(.+?)<\/a>/i', $file, $match);
    $data['area'] = trim(strip_tags($match[1]));

    return $data;
  }

  //获取章节列表
  public function getChapters($file, $info) {
    $this->url = $info['link'];
    $this->parse_url = parse_url($this->url);
    switch($this->parse_url['host']) {
      case 'www.leshen.com':
        $result = $this->getChapters_leshen($file, $info); break;
      default:
        $result = array(); break;
    }

    return $result;
  }

  public function getChapters_leshen($file, $info)
  {
    $data = array();
    $data['count'] = 0;
    $data['list'] = array();

    $file = iconv('gb2312', 'utf-8//IGNORE', $file);
    preg_match_all('/<h3>(.+?)<\/h3>/is', $file, $matches);
    preg_match_all('/<div.+?class="plist pnormal">(.+?)<\/div>/is', $file, $matches2);

    if(count($matches[1]) == 0) {
      return array('error'=>true, 'msg'=>'match zero');
    }

    if(count($matches[1]) != count($matches2[1])) {
      return array('error'=>true, 'count1'=>count($matches[1]), 'count2'=>count($matches2[1]));
    }

    foreach ($matches[1] as $key => $title) {
      $title = strip_tags($title);
      preg_match_all('/href="(.+?)">(.+?)<\/a>/i', $matches2[1][$key], $matches3);
      foreach ($matches3[1] as $k => $v) {
        if(!stristr($v, 'http://')) {
          $v = 'http://'.$this->parse_url['host'].$v;
        }
        $t = strip_tags($matches3[2][$k]);
        if(mb_substr($t, 0, 1, 'utf8') == '第') {
          $t = ltrim($t, '第');
        }
        if($key == 0 && $k == 0) {
          $data['last'] = array($v, $t);
        }
        $data['list'][$title][$v] = $t;
        $data['count']++;
      }
    }
    
    return $data;
  }

  //获取漫画列表
  public function getList($file, &$info)
  {
    $this->url = $info['link'];
    $this->parse_url = parse_url($this->url);
    switch($this->parse_url['host']) {
      case 'www.leshen.com':
        $result = $this->getList_leshen($file, $info); break;
      default:
        $result = array(); break;
    }

    return $result;
  }

  public function getList_leshen($file, &$info)
  {
    $result = array();
    $file = iconv('gb2312', 'utf-8//IGNORE', $file);
    if(empty($file)) {
      return array('error'=>true);
    }

    preg_match('/<div id="dmList"[^>]*>(.+?)<\/ul>/is', $file, $match);
    preg_match_all('/<li[^>]*>(.+?)<\/li>/is', $match[1], $matches);
    foreach ($matches[1] as $item) {
      $data = array();

      preg_match('/src="(.+?)"/i', $item, $out);
      $data['thumb'] = strstr($out[1], 'http://') ? $out[1] : 'http://'.$this->parse_url['host'].$out[1];

      preg_match('/href="(.+?)"/i', $item, $out);
      $data['link'] = strstr($out[1], 'http://') ? $out[1] : 'http://'.$this->parse_url['host'].$out[1];

      preg_match('/<dt><a[^>]*>(.+?)<\/a>/i', $item, $out);
      $data['title'] = strip_tags($out[1]);
      $data['title'] = str_replace('漫画', '', $data['title']);
      $data['pinyin'] = Pinyin($data['title']);
      if(empty($data['pinyin'])) {
        $data['pinyin'] = getMD5($data['title']);
      }

      preg_match('/<\/em><span class=".+?">(.+?)<\/span>/i', $item, $out);
      $data['status'] = (string) $out[1];

      preg_match('/<p class="intro">(.+?)<\/p>/is', $item, $out);
      preg_match('/<\/em>(.+?)<\/p>/i', $out[0], $out2);
      $data['info'] = (string) $out2[1];
      $data['info'] = strip_tags($data['info']);
      $data['type'] = $info['type'];

      $result[] = $data;
    }

    return $result;
  }
}